package com.example.servlet;

import com.example.dao.StudentMapper;
import com.example.pojo.StuClass;
import com.example.pojo.Student;
import com.example.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public class getStudentsByNameServelt extends HttpServlet {

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        Map<String, Object> params = new HashMap<>();

        int stu_id;
        String stu_id_param = request.getParameter("stu_id");
        if (stu_id_param != null && !stu_id_param.isEmpty()) {
            stu_id = Integer.parseInt(stu_id_param);
            params.put("stu_id", stu_id);
        } else {
            params.put("stu_id", null);
        }

        String stu_name = request.getParameter("stu_name");
        params.put("stu_name", stu_name);
        int stu_no;
        String stu_no_param = request.getParameter("stu_no");
        if (stu_no_param != null && !stu_no_param.isEmpty()) {
            stu_no = Integer.parseInt(stu_no_param);
            params.put("stu_no", stu_no);
        } else {
            params.put("stu_no", null);
        }

        String class_name = request.getParameter("class_name");
        int class_id;
        if (class_name != null && !class_name.isEmpty()) {
            //将class_name转为class_id
            SqlSession sqlSession1 = MybatisUtils.getSqlSession();
            StudentMapper mapper1 = sqlSession1.getMapper(StudentMapper.class);
            StuClass stuClass = mapper1.getClassByClassName(class_name);
            class_id = stuClass.getClass_id();
            params.put("class_id", class_id);
        } else {
            params.put("class_id", null);
        }


        // 调用MyBatis执行查询
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        try {
            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
            List<Student> students = studentMapper.getStudentsByName(params);

            // 处理查询结果...
            // 存储查询结果到请求属性中
            request.setAttribute("studentList", students);

            // 转发到user.jsp显示结果
            request.getRequestDispatcher("search.jsp").forward(request, response);
        } finally {
            sqlSession.close();
        }

}}
